module Remote

  class Server
    def initialize url
      @url = url
    end

    def ask url, question, params = {}
      JSON.parse AppEngine::URLFetch::HTTP.get(
        make_uri(url, question, params))
    end

    def ask_file url, question, params = {}
      FileResponse.new(
        AppEngine::URLFetch.fetch(
          make_uri(url, question, params).to_s, {
            :method => 'GET',
            :deadline => 25
        }))
    end

    def make_uri url, question, params = {}
      query =
        Rack::Utils.build_query(:json => {
          :name => question,
          :params => params
        }.to_json)

      URI.parse(@url+url+'?'+query).tap { |u| puts u.to_s }
    end


    class FileResponse
      def initialize source
        @_source = source
      end

      def data
        @_source.body
      end

      def info
        JSON.parse @_source.header['X-bublifuk-json']
      end
    end
  end
  
end